/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.tablefield.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.databaseinfo.service.impl.BiDataSource;
import vip.xiaonuo.modular.tablefield.entity.TableField;
import vip.xiaonuo.modular.tablefield.enums.TableFieldExceptionEnum;
import vip.xiaonuo.modular.tablefield.mapper.TableFieldMapper;
import vip.xiaonuo.modular.tablefield.param.TableFieldParam;
import vip.xiaonuo.modular.tablefield.service.TableFieldService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * 数据库信息表service接口实现类
 *
 * @author wfy
 * @date 2022-07-05 16:32:16
 */
@Service
public class TableFieldServiceImpl extends ServiceImpl<TableFieldMapper, TableField> implements TableFieldService {

    @Override
    public PageResult<TableField> page(TableFieldParam tableFieldParam) {
        QueryWrapper<TableField> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(tableFieldParam)) {

            // 根据数据库id 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getDatabaseId())) {
                queryWrapper.lambda().like(TableField::getDatabaseId, tableFieldParam.getDatabaseId());
            }
            // 根据指标名称id 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getIndicatorsNameId())) {
                queryWrapper.lambda().eq(TableField::getIndicatorsNameId, tableFieldParam.getIndicatorsNameId());
            }
            // 根据主数据指标id 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getMasterDataId())) {
                queryWrapper.lambda().eq(TableField::getMasterDataId, tableFieldParam.getMasterDataId());
            }
            // 根据字段权限分级 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getColumnPermissions())) {
                queryWrapper.lambda().eq(TableField::getColumnPermissions, tableFieldParam.getColumnPermissions());
            }
            // 根据字段名 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getColumnName())) {
                queryWrapper.lambda().eq(TableField::getColumnName, tableFieldParam.getColumnName());
            }
            // 根据字段备注 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnRemarks())) {
                queryWrapper.lambda().eq(TableField::getCloumnRemarks, tableFieldParam.getCloumnRemarks());
            }
            // 根据字段类型 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnType())) {
                queryWrapper.lambda().eq(TableField::getCloumnType, tableFieldParam.getCloumnType());
            }
            // 根据字段长度 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnLength())) {
                queryWrapper.lambda().eq(TableField::getCloumnLength, tableFieldParam.getCloumnLength());
            }
            // 根据索引 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnIndex())) {
                queryWrapper.lambda().eq(TableField::getCloumnIndex, tableFieldParam.getCloumnIndex());
            }
            // 根据字段所在的Catalog名字 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnCatalogName())) {
                queryWrapper.lambda().eq(TableField::getCloumnCatalogName, tableFieldParam.getCloumnCatalogName());
            }
            // 根据字段小数点后的位数 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnScale())) {
                queryWrapper.lambda().eq(TableField::getCloumnScale, tableFieldParam.getCloumnScale());
            }
            // 根据字段是否自动递增 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnIsAuto())) {
                queryWrapper.lambda().eq(TableField::getCloumnIsAuto, tableFieldParam.getCloumnIsAuto());
            }
            // 根据字段是否是主键 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnIsPrimary())) {
                queryWrapper.lambda().eq(TableField::getCloumnIsPrimary, tableFieldParam.getCloumnIsPrimary());
            }
            // 根据字段在数据库中是否为货币型 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnIsCurrency())) {
                queryWrapper.lambda().eq(TableField::getCloumnIsCurrency, tableFieldParam.getCloumnIsCurrency());
            }
            // 根据字段是否为空 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnIsNullable())) {
                queryWrapper.lambda().eq(TableField::getCloumnIsNullable, tableFieldParam.getCloumnIsNullable());
            }
            // 根据字段是否为只读 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnIsReadonly())) {
                queryWrapper.lambda().eq(TableField::getCloumnIsReadonly, tableFieldParam.getCloumnIsReadonly());
            }
            // 根据字段是否出现在where中 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getCloumnIsSearchable())) {
                queryWrapper.lambda().eq(TableField::getCloumnIsSearchable, tableFieldParam.getCloumnIsSearchable());
            }
            // 根据访问权限 查询
            if (ObjectUtil.isNotEmpty(tableFieldParam.getPermissions())) {
                queryWrapper.lambda().eq(TableField::getPermissions, tableFieldParam.getPermissions());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<TableField> list(TableFieldParam tableFieldParam) {
        return this.list();
    }

    @Override
    public void add(TableFieldParam tableFieldParam) {
        TableField tableField = new TableField();
        BeanUtil.copyProperties(tableFieldParam, tableField);
        this.save(tableField);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<TableFieldParam> tableFieldParamList) {
        tableFieldParamList.forEach(tableFieldParam -> {
            this.removeById(tableFieldParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(TableFieldParam tableFieldParam) {
        TableField tableField = this.queryTableField(tableFieldParam);
        BeanUtil.copyProperties(tableFieldParam, tableField);
        this.updateById(tableField);
    }

    @Override
    public TableField detail(TableFieldParam tableFieldParam) {
        return this.queryTableField(tableFieldParam);
    }

    /**
     * 获取数据库信息表
     *
     * @author wfy
     * @date 2022-07-05 16:32:16
     */
    private TableField queryTableField(TableFieldParam tableFieldParam) {
        TableField tableField = this.getById(tableFieldParam.getId());
        if (ObjectUtil.isNull(tableField)) {
            throw new ServiceException(TableFieldExceptionEnum.NOT_EXIST);
        }
        return tableField;
    }

    @Override
    public void export(TableFieldParam tableFieldParam) {
        List<TableField> list = this.list(tableFieldParam);
        PoiUtil.exportExcelWithStream("SnowyTableField.xls", TableField.class, list);
    }

    public static boolean setTaleFiledRe(BiDataSource dataSource,TableFieldParam tableFieldParam ) throws SQLException {
        Properties connectionProps = new Properties();
        connectionProps.put("user", dataSource.username);
        connectionProps.put("password", dataSource.password);
        connectionProps.put("remarks", "true");
        connectionProps.put("useInformationSchema", "true");
        try {
            Connection connection = DriverManager.getConnection(dataSource.url, connectionProps);
            Statement Statement = connection.createStatement();
            String tableName = tableFieldParam.getCloumnCatalogName();
            String filedName = tableFieldParam.getColumnName();
            String filedType = tableFieldParam.getCloumnType();
            String filedLength = tableFieldParam.getCloumnLength();
            String filedRemarks = tableFieldParam.getCloumnRemarks();
            String setFiledReSql = "alter table "+tableName+" MODIFY  "+filedName+" "+filedType+"("+ filedLength+") COMMENT '"+filedRemarks+"'";
            System.out.println("[DEBUG] TableFieldServiceImpl.java -> setTaleFiledRe : setFiledReSql= "+setFiledReSql);
            Statement.executeUpdate(setFiledReSql);
        }catch (Exception e){
            System.err.println("[ERROR] TableInfoServiceImpl.java->setTaleRe : error = " +e.toString());
            return  false;
        }
        return true;
    }
}
